package com.swak.telnet.cmd;

import java.io.Serializable;

import com.swak.reactivex.transport.Message;
import com.swak.utils.StringUtils;

import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;

@Getter
@Setter
@Accessors(chain = true)
public class Command implements Serializable {

	private static final long serialVersionUID = 1L;

	private static final CommandParser Parser = new CommandParser();

	/**
	 * 命令
	 */
	private String command;

	/**
	 * 参数
	 */
	private Args args = new Args();

	/**
	 * 选项
	 */
	private Options options = new Options();

	/**
	 * 当前的选项
	 * 
	 * @return
	 */
	public Option currentOption() {
		return options.last();
	}

	/**
	 * 新的选项
	 * 
	 * @return
	 */
	public Command newOption(String name) {
		options.add(new Option().setName(name));
		return this;
	}

	public Message toMessage() {
		Message message = Message.forRequest().addOption(Message.TwoWay);
		Long id = this.options.getLong(Message.Id);
		Byte option = this.options.getByte(Message.Option);
		Byte status = this.options.getByte(Message.Status);

		if (id != null) {
			message.setId(id);
		}
		if (option != null) {
			message.setOption(option);
		}
		if (status != null) {
			message.setStatus(status);
		}
		message.setData(this);
		return message;
	}

	@Override
	public String toString() {
		StringBuilder cmd = new StringBuilder();
		cmd.append(this.command);
		if (!this.args.isEmpty()) {
			cmd.append(StringUtils.SPACE).append(StringUtils.join(this.args, StringUtils.SPACE));
		}
		cmd.append(StringUtils.SPACE).append(this.options);
		return cmd.toString();
	}

	/**
	 * 命令解析
	 * 
	 * @param message
	 * @return
	 */
	public static Command parse(String message) {
		return Parser.parse(message);
	}
}
